package com.example.android.stargazeeffect;

import android.content.Context;
import android.graphics.Canvas;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class StarGazeView extends SurfaceView implements SurfaceHolder.Callback
{
	private final int STARS = 300;
	private StarGazeThread _thread = null;
	private Star[] _stars = null;
	
	public StarGazeView(Context context, int width, int height)
	{
		super(context);
			
		getHolder().addCallback(this);
		
		_thread = new StarGazeThread(getHolder(), this);
	
		_stars = new Star[STARS];
		
		for(int i = 0; i < STARS; i++)
		{
			_stars[i] = new Star(width, height);
		}
	}
	
	@Override public void onDraw(Canvas canvas)
	{
		canvas.drawRGB(0, 0, 0);
		
		for(int i = 0; i < STARS; i++)
		{
			_stars[i].draw(canvas);
		}
	}
	
	
	@Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) 
	{
		
	}

	@Override public void surfaceCreated(SurfaceHolder holder) 
	{
		_thread.setRunning(true);
		_thread.start();
	}

	@Override public void surfaceDestroyed(SurfaceHolder holder) 
	{		
		boolean retry = true;
		
		_thread.setRunning(false);
		
		while(retry)
		{
			try
			{
				_thread.join();
				retry = false;
			}
			catch(InterruptedException e)
			{
				
			}
		}
	}
}
